from PyQt5.QtCore import QThread, pyqtSignal
from yt_dlp import YoutubeDL
from utils import *


class InfoExtractor(QThread):
    info_result = pyqtSignal(dict)
    fail_result = pyqtSignal()
    def __init__(self, parent):
        super().__init__(parent=parent)
        self.url = ''


    def run(self) -> None:
        ydl_opts = {
            'quiet': False,
            'extract_flat': True,  # 为 True 时不会解析分辨率
            'skip_download': True,
            'nocheckcertificate': True,
            # 如果有 cookies 文件也可以加上这一行
            'force_ipv4': True,
            'http_headers': {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            },
            # 如果有 cookies 文件也可以加上这一行
            'cookiefile': 'cookies.txt',
        }
        with YoutubeDL(ydl_opts) as ydl:
            try:
                info = ydl.extract_info(self.url, download=False)
                write_log(info, 'info')
                self.info_result.emit(info)
            except Exception as e:
                print(str(e))
                self.fail_result.emit()



    def extract(self, url):
        self.url = url
        self.start()